package com.hqyj.system.shiro;


import com.hqyj.system.model.User;
import com.hqyj.system.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;

import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;

import org.apache.shiro.realm.AuthorizingRealm;

import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @ClassName CustomRealm
 * @Description
 * @Author zlf
 * @Date 2021/9/17 14:14
 * @Version 1.0
 **/

public class CustomRealm extends AuthorizingRealm {
    @Autowired
    public UserService userService;
    //1.认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //1.认证
        // ---->第一步从token中取出身份信:token是用户输入的
        String username = (String) authenticationToken.getPrincipal();
        System.out.println("-------------------AuthenticationInfo----------" + username);
        // ---->第二步（查询数据库）:根据用户输入的userCode从查询数据
        User user_db = userService.queryUserByUsername(username);
        System.out.println("-------------------AuthenticationInfo----------" + user_db);
        // 如果查询不到返回null
        if (user_db == null) {
            return null;
        }
        //获取当前用户的会话域
        Session session = SecurityUtils.getSubject().getSession();
        //把登录用户信息保存到Session
        session.setAttribute("USER", user_db);
        //准备值
        String password = user_db.getPassword();
        //设置realm的名称
        String realmName = this.getName();
        //盐
        String salt = user_db.getSalt();

        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(username,
                password, ByteSource.Util.bytes(salt), realmName);
        return simpleAuthenticationInfo;
    }

    //2.授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        return null;
    }

}
